package com.auto.survey.activity.test

import android.bluetooth.BluetoothDevice
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.bluetooth.BluetoothManagerUtil
import com.auto.survey.activity.bluetooth.BluetoothService
import com.auto.survey.base.BaseActivity
import com.auto.survey.base.Command
import com.auto.survey.util.Helper
import com.auto.survey.widget.CommonTitle.Companion.TEXT_POSITON_RIGHT
import com.google.gson.Gson
import kotlinx.coroutines.launch

class TestActivity: BaseActivity() {

    private val bluetoothManager by lazy {
        BluetoothManagerUtil.getInstance(this)
    }
    private lateinit var drawerLayout:DrawerLayout
    private lateinit var drawerAdapter:DrawerAdapter

    private var resultCallback: ((String) -> Unit)? = null
    private val viewModel:TestViewModle by viewModels()
    private val drawerData = mutableListOf<String>()

    override fun initView() {

        // 绑定Service
        bluetoothManager.bindService()

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.blue)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.blue)
        mComment_title?.setTitle("测试页面")

        mComment_title?.setRightTitle("查看接收消息")
        mComment_title?.setTitleColor(Color.WHITE, TEXT_POSITON_RIGHT)
        mComment_title?.setOnRightTextClickListener{
            if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
                drawerLayout.closeDrawer(GravityCompat.END)
            } else {
                drawerLayout.openDrawer(GravityCompat.END)
            }
        }


        drawerLayout = findViewById(R.id.drawer_layout)
        val edittext = findViewById<EditText>(R.id.edit_test)
        val temp = "\n%R1Q,2116:1000,1\r\n"
        edittext.setText(temp)
        var editreltlist:MutableList<String>?=null
        findViewById<TextView>(R.id.tv_send_test).setOnClickListener(Helper.debounce {
            editreltlist = mutableListOf()
            var tempStr = edittext.text.toString()
            if (TextUtils.isEmpty(tempStr)) {
                tempStr = Command.COM_NullProc
            }

            val log = "发送数据命令：$tempStr"
            editreltlist!!.add(log)
            sendBlueData(tempStr)
        })


        val rvtest = findViewById<RecyclerView>(R.id.rv_test)
        rvtest.layoutManager = LinearLayoutManager(this@TestActivity)
        val adapter = TestAdapter(this@TestActivity, bluetoothManager, viewModel)
        rvtest.adapter = adapter
        testData().let { adapter.setItems(it) }


        val rvdrawer = findViewById<RecyclerView>(R.id.rv_test_drawer)
        rvdrawer.layoutManager = LinearLayoutManager(this@TestActivity)
        drawerAdapter = DrawerAdapter()
        rvdrawer.adapter = drawerAdapter


        Handler(Looper.getMainLooper()).postDelayed(kotlinx.coroutines.Runnable {
            // 注册回调
            bluetoothManager.registerCallback(object : BluetoothService.ConnectionCallback{
                override fun onDiscoverDeviceState(isdiscovery: Boolean) {
                }

                override fun onConnectionStateChanged(
                    device: BluetoothDevice,
                    state: BluetoothService.ConnectionState
                ) {
                }

                override fun onDataReceived(device: BluetoothDevice, data: ByteArray) {

                    val utf_8_str = String(data, charset(Charsets.UTF_8.toString()))
                    Log.i("TestActivity", "utf_8_str == $utf_8_str")
                    if (editreltlist != null) {
                        val log = "收到返回数据：$utf_8_str"
                        editreltlist?.add(log)
                        viewModel.getBlueToothCommunity(editreltlist!!)
                        editreltlist = null
                    }

                    resultCallback?.invoke(utf_8_str)
                }

                override fun onError(message: String) {
                    resultCallback?.invoke(message)
                }

            })
        }, 1000)


        lifecycleScope.launch {
            viewModel.blueToothCommunity.observe(this@TestActivity) { it->
                if (it != null && it.isNotEmpty()) {
                    Log.i("TestActivity", "lifecycleScope result = ${Gson().toJson(it)}")
                    drawerData.addAll(it)
                    drawerAdapter.setDrawerItems(drawerData)
                }
            }
        }
    }

    private fun sendBlueData(tempStr:String) {
        Log.i("TestActivity", "sendBlueData ## $tempStr")
        if (null  != bluetoothManager.getConnectedDevices2() && bluetoothManager.getConnectedDevices2().size>0 ) {
            val temp = bluetoothManager.getConnectedDevices2()[0]
            bluetoothManager.sendDataByClient(temp, tempStr.toByteArray())
        }
    }

    private fun testData(): MutableList<Map<String, List<String>>> {

        val list = mutableListOf<Map<String, List<String>>>()
        val map1 = HashMap<String, List<String>>()
        map1["验证当前设备与手机通信是否畅通"] = listOf(Command.COM_NullProc)
        list.add(map1)

        val map2 = HashMap<String, List<String>>()
        map2["开始全站仪水平转动"] = listOf(Command.MOT_StartController, Command.MOT_SetVelocity)
        list.add(map2)

        val map3 = HashMap<String, List<String>>()
        map3["停止全站仪转动"] = listOf(Command.MOT_StopController)
        list.add(map3)

        val map4 = HashMap<String, List<String>>()
        map4["查询全站仪的精度等级"] = listOf(Command.CSV_GetDeviceConfig)
        list.add(map4)

        val map5 = HashMap<String, List<String>>()
        map5["获取全站仪的型号名称"] = listOf(Command.CSV_GetInstrumentName)
        list.add(map5)

        val map6 = HashMap<String, List<String>>()
        map6["获取全站仪出厂序列号"] = listOf(Command.CSV_GetInstrumentNo)
        list.add(map6)

        val map7 = HashMap<String, List<String>>()
        map7["获取全站仪的内部温度"] = listOf(Command.CSV_GetIntTemp)
        list.add(map7)

        val map8 = HashMap<String, List<String>>()
        map8["获取全站仪当前日期和时间"] = listOf(Command.CSV_GetDateTime)
        list.add(map8)

        val map9 = HashMap<String, List<String>>()
        map9["查询全站仪的自动关机配置参数"] = listOf(Command.SUP_GetConfig)
        list.add(map9)

        val map10 = HashMap<String, List<String>>()
        map10["获取仪器的测站坐标"] = listOf(Command.TMC_GetStation)
        list.add(map10)
        return list
    }

    // 设置回调
    fun setResultCallback(callback: (String) -> Unit) {
        this.resultCallback = callback
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_check
    }


}